﻿using System;
using System.Text.RegularExpressions;

namespace Qzb.DBHelper.Utilities
{
    public class ConvertUtils
    {
        /// <summary>
        /// 将 Object 对象转换为指定类型的对象
        /// </summary>
        /// <param name="value">源数据</param>
        /// <param name="conversionType">要返回对象的类型</param>
        /// <returns></returns>
        public static object ChangeType(object value, Type conversionType)
        {
            if (value == null)
                return null;

            try
            {
                if (!conversionType.IsGenericType)
                {
                    return Convert.ChangeType(value, conversionType);
                }
                else
                {
                    var genericTypeDefinition = conversionType.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(Nullable<>))
                    {
                        return Convert.ChangeType(value, Nullable.GetUnderlyingType(conversionType));
                    }
                }
                return null;
            }
            catch
            {
                throw new InvalidCastException($"从类型 \"{value.GetType().FullName}\" 转换为 \"{conversionType.FullName}\" 无效。");
            }
        }

        /// <summary>
        /// 将Object对象转换为指定类型的对象
        /// </summary>
        /// <typeparam name="T">要返回对象的类型</typeparam>
        /// <param name="value">源数据</param>
        /// <param name="objDefault">返回对象的默认值</param>
        /// <returns>返回指定的对象T</returns>
        public static T ChangeType<T>(object value, T objDefault = default(T))
        {
            if (null == value)
                return objDefault;

            try
            {
                var obj = ChangeType(value, typeof(T));
                if (obj == null)
                    return objDefault;

                return (T)obj;
            }
            catch
            {
                throw new InvalidCastException($"从类型 \"{value.GetType().FullName}\" 转换为 \"{typeof(T).FullName}\" 无效。");
            }
        }

        /// <summary>
        /// 转换sql中的占位符
        /// </summary>
        /// <param name="sql">Sql脚本</param>
        /// <param name="placeHolder">占位符</param>
        /// <returns>转后的Sql</returns>
        public static string ConvertSqlPlaceHolderOfSqlStatement(string sql, string placeHolder)
        {
            var regex = new Regex(@"@(\w+)");
            return regex.Replace(sql, placeHolder);
        }
    }
}
